package org.pasta.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

	FilterConfig config;
	
	List exceptionPage;
	
	
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
		exceptionPage = new ArrayList();
		exceptionPage.add("/login.html");
		/*exceptionPage.add("/UserGroupRegisDetail.denso");
		exceptionPage.add("/UserGroupRegisDisplay.denso");
		exceptionPage.add("/UserGroupRegisEditor.denso");*/
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {	
		HttpServletRequest httpRequest  = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
		
		StringBuffer basePath = new StringBuffer();
		basePath.append(httpRequest.getScheme());
		basePath.append("://");
		basePath.append(httpRequest.getServerName());
		basePath.append(":");
		basePath.append(httpRequest.getServerPort());
		basePath.append(httpRequest.getContextPath());
		basePath.append("/");
		
        String requestURL = httpRequest.getRequestURL().toString();
        //String pageName = requestURL.substring(requestURL.lastIndexOf("/")+1);
        
		HttpSession session = httpRequest.getSession();
		Object user = session.getAttribute("login-user");
		
		if(null == user)
		{
			String exceptURL = null;
			int exceptSize = getExceptionPage().size();
			for(int i = 0 ; i < exceptSize ; i++)
			{
				exceptURL = (String) getExceptionPage().get(i);
				if(requestURL.indexOf(exceptURL) >= 0)
				{
					chain.doFilter(request,response);
					return;
				}
			}
			httpResponse.sendRedirect(basePath.toString()+"login.html");
			return;
		}
		chain.doFilter(request,response);
	}

	public void destroy() {
		
	}

	public List getExceptionPage() {
		return exceptionPage;
	}

	public FilterConfig getConfig() {
		return config;
	}

}
